<?php
namespace app\api\controller;

use app\admin\model\AuthRule;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\MoneyLog;
use fast\Tree;
use think\Db;
use think\exception\PDOException;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function list(){

    }

    /**
     * 用户设备续费（B C）
     * @ApiMethod (POST)
     *用户设备页接口已经有需要的信息了此接口理论上无需调用
     */
    public function machineRenew()
    {
        $machineid = $this->request->post("machineid");
        if($machineid){
            $where['user_id']=['=',$this->auth->getUserinfo()['id']];
            $where['id']=['=',$machineid];
            $re=$machinecountre=\app\admin\model\Machine::where($where)->find();
            $this->success(__('获取成功'), $re);
        }else{
            $this->error(__('获取失败'));
        }

    }

    /**
     * 确认订单（B C）
     * @ApiMethod (POST)
     */
    public function confirmOrder()
    {
        $where['id']=['=',$this->request->post("goodsid")];
        $where['state']=['=',1];
        $where['stock']=['>=',$this->request->post("quantity")];

        $goodsinfo=\app\admin\model\Goods::where($where)->find();

        $userinfo=$this->auth->getUser();

        $pay_price=$goodsinfo['goods_price']*$this->request->post("quantity");

        if($userinfo['money'] - $pay_price<0){
            $this->error(__('余额不足。'));
        }


        if($goodsinfo && $this->request->post("quantity")>=1) {
            $result = false;
            Db::startTrans();
            try {
                $orderdata['user_id']=$this->auth->getUserinfo()['id'];
                $orderdata['goods_id']=$this->request->post("goodsid");
                $orderdata['order_sn']=$orderdata['user_id'].date('YmdHis').$orderdata['goods_id'].rand(1000000,9999999);
                $orderdata['quantity']=$this->request->post("quantity");
                $orderdata['pay_price']=$goodsinfo['goods_price']*$orderdata['quantity'];
                $orderdata['state']=0;
                $orderdata['admin_id']=$goodsinfo['admin_id'];
                $orderdata['createtime']=time();

                $model=new \app\admin\model\Order;
                $result = $model->allowField(true)->save($orderdata);
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        if ($result !== false) {
            $params['order_sn']=$model->order_sn;
            $this->success('订单创建成功',$params);
        } else {
            $this->error(__('订单创建失败'));
        }
    }


    /**
     * 订单手写签名确认图片实际支付（B C） 弃用
     * @ApiMethod (POST)
     */
//    public function orderAutograph()
//    {
//        $order_sn=$this->request->post("order_sn");
//        $autograph_image=$this->request->post("autograph_image");
//
//        $model=new \app\admin\model\Order;
//        $orderinfo=$model->where('order_sn',$order_sn)->find();
//
//        $userinfo=$this->auth->getUserinfo();
//        $goodsinfo=\app\admin\model\Goods::where('id',$orderinfo['goods_id'])->find();
//
//        $result = false;
//        if($orderinfo && !$orderinfo['autograph_image'] && $userinfo['money'] - $orderinfo['pay_price']>=0 && $goodsinfo) {
//            Db::startTrans();
//            try {
//                //修改订单状态
//                $model->where('order_sn',$order_sn)->update(['autograph_image' => $autograph_image,'state' =>1]);
//                //创建钱包记录
//                MoneyLog::create(['user_id' => $userinfo['id'], 'money' =>  -$orderinfo['pay_price'], 'before' => $userinfo['money'], 'after' => $userinfo['money'] - $orderinfo['pay_price'], 'memo' => '购买设备消费']);
//                //修改用余额
//                \app\admin\model\User::where('id',$userinfo['id'])->update(['money'=>$userinfo['money'] - $orderinfo['pay_price']]);
//                //扣除商品库存
//                \app\admin\model\Goods::where('id',$orderinfo['goods_id'])->update(['stock'=>$goodsinfo['stock']-1]);
//
//                Db::commit();
//                $result = true;
//            } catch (PDOException $e) {
//                Db::rollback();
//                $this->error($e->getMessage());
//            } catch (Exception $e) {
//                Db::rollback();
//                $this->error($e->getMessage());
//            }
//        }
//        if ($result !== false) {
//            $this->success('签名支付成功',$autograph_image);
//        } else {
//            $this->error(__('签名支付失败，未扣币。'));
//        }
//    }

    /**
     * 购买支付接口支付（B C）
     * @ApiMethod (POST)
     */
    public function orderPayment()
    {
        $order_sn=$this->request->post("order_sn");
        $pay_password=$this->request->post("pay_password");

        $userinfo=$this->auth->getUser();
        $pay_password_find=\app\admin\model\User::where('id',$userinfo['id'])->field('id,paypassword,paypasswordsalt')->find();

        $orderModel=new \app\admin\model\Order;
        $orderinfo= $orderModel->where(['order_sn'=>$order_sn,'user_id'=>$userinfo['id'],'state'=>0])->find();

        $where['id']=['=',$orderinfo['goods_id']];
        $where['state']=['=',1];
        $where['stock']=['>=',$orderinfo['quantity']];
        $goodsinfo=\app\admin\model\Goods::where($where)->find();


        $md5_input_pay_password= md5(md5($pay_password) . $pay_password_find['paypasswordsalt']);

        $result = false;

        if(!$orderinfo){
            $this->error(__('订单不存在。'));
        }
        if(!$goodsinfo){
            $this->error(__('商品状态异常。'));
        }
        if($userinfo['money'] - $orderinfo['pay_price']<0){
            $this->error(__('余额不足。'));
        }

        if($md5_input_pay_password==$pay_password_find['paypassword']) {
            $user_model=new \app\admin\model\User;
            Db::startTrans();
            try {
                //修改订单状态
                $orderModel->where('order_sn',$order_sn)->update(['state' =>1]);
                //创建钱包记录
                MoneyLog::create(['user_id' => $userinfo['id'], 'money' =>  -$orderinfo['pay_price'], 'before' => $userinfo['money'], 'after' => $userinfo['money'] - $orderinfo['pay_price'], 'memo' => '购买设备消费']);
                //修改用户余额

                \app\admin\model\User::where('id',$userinfo['id'])->update(['money'=>$userinfo['money'] - $orderinfo['pay_price']]);
                //用户自购之后升级成为会员
                if($userinfo['distribution_id']==-1){
                    \app\admin\model\User::where('id',$userinfo['id'])->update(['distribution_id'=>0]);
                }
                //扣除商品库存
                \app\admin\model\Goods::where('id',$orderinfo['goods_id'])->update(['stock'=>$goodsinfo['stock']-$orderinfo['quantity']]);


                //查找出这名用户的上级
                $user_parent_find=\app\admin\model\User::where('id',$userinfo['pid'])->where('distribution_id','<>',-1)->find();

                $u_buy_s=23;//查找设置的最低消费节点
                $u_buy_b=10/100;//查找邀请消费分销比例

                //if判断用户是否有上级
                if($user_parent_find){

                    $u_p_all_c_buy_number=$user_parent_find['c_buy_number']+$orderinfo['quantity']; //获得此时用户父级所有的购买数量
                    $u_p_all_rebate=$orderinfo['pay_price']*$u_buy_b;//邀请消费分U总数额

                    //父级用户更新数据
                    $up_user_parent_data=[
                        'id'=>$userinfo['pid'],
                        'money'=>$user_parent_find['money']+$u_p_all_rebate,
                        'c_buy_number'=>$u_p_all_c_buy_number,
                    ];
                    //判断用户父级够不够升级成为底级的分销身份，然后写入用户父级能不能升级的更新数据
                    $u_p_all_c_buy_number>=$u_buy_s && $user_parent_find['distribution_id']==0 ? $up_user_parent_data['distribution_id']=5 : 1;
                    //执行父级数据更新
                    $user_model->where('id',$userinfo['pid'])->update($up_user_parent_data);

                    //用户父级钱包邀请消费分U记录创建
                    MoneyLog::create(['user_id' => $userinfo['pid'], 'money' => $u_p_all_rebate, 'before' => $user_parent_find['money'], 'after' => $up_user_parent_data['money'], 'memo' => '邀请消费分U']);


                    //查询该用户的父级链
                    $u_ps_sel=\app\admin\model\User::where('id','in',$userinfo['pids'])->select();
                    //颠倒顺序从最底级的直接父级开始
                    $u_ps_sel=array_reverse($u_ps_sel);
                    //查询所有分销身份
                    $a_distribution_sel=\app\admin\model\DistributionInfo::order('id desc')->select();

                    foreach ($a_distribution_sel as $k => $v) {
                        foreach ($u_ps_sel as $key => $value) {
                            $count=\app\admin\model\User::where('pid',$value['id'])->where('distribution_id',$v['id'])->count();
                            $this_user_find=\app\admin\model\User::where('id',$value['id'])->where('distribution_id',-1)->find();
//                            if($value['id']){
//                                 dump('当前等级id'.$v['id'].'---'.'当前用户id'.$value['id'].'---'.'当前同级数量'.$count.'---'.''.$v['promotion_conditions']);
//                            }
                            if(!$this_user_find && $count>=$v['promotion_conditions'] && $v['promotion_conditions']){
                                $user_model->where('id',$value['id'])->update(['distribution_id'=>$v['pid']]);

                            }
                        }
                    }


                    //获取最新的用户父级信息
                    $user_parent_find=\app\admin\model\User::where('id',$userinfo['pid'])->find();
                    if(isset($up_user_parent_data['distribution_id'])){
                        $fenxiaogoods_number=$user_parent_find['c_buy_number']-$u_buy_s;
                    }else{
                        $fenxiaogoods_number=$orderinfo['quantity'];
                    }
                    //查找这个用户上级的分销身份
                    $user_parent_DistributionInfo_find = \app\admin\model\DistributionInfo::where('id',$user_parent_find['distribution_id'])->find();

                    //判断这名上级是否有分销身份
                    if($user_parent_DistributionInfo_find){
                        //向上找到最近的一个经理和总监分U
                        $jingli_find=\app\admin\model\User::order('id desc')->where('id','in',$userinfo['pids'])->where('distribution_id',5)->field('id,money')->find();
                        $zongjian_find=\app\admin\model\User::order('id desc')->where('id','in',$userinfo['pids'])->where('distribution_id',4)->field('id,money')->find();

                        if($jingli_find){
                            $jingli_data=[
                                'id'=>$jingli_find['id'],
                                'money'=>$jingli_find['money']+$fenxiaogoods_number*30,
                            ];
                            $user_model->where('id',$jingli_find['id'])->update(['money'=>$jingli_data['money']]);
                            //经理分销身份分U记录创建
                            MoneyLog::create(['user_id' => $jingli_find['id'], 'money' => $fenxiaogoods_number*30, 'before' => $jingli_find['money'], 'after' => $jingli_data['money'], 'memo' => '分销身份分U']);

                        }
                        if($zongjian_find && $jingli_find){
                            $zongjian_data=[
                                'id'=> $zongjian_find['id'],
                                'money'=>$zongjian_find['money']+$fenxiaogoods_number*20,
                            ];
                            $user_model->where('id',$zongjian_find['id'])->update(['money'=>$zongjian_data['money']]);
                            //总监分销身份分U记录创建
                            MoneyLog::create(['user_id' => $zongjian_find['id'], 'money' => $fenxiaogoods_number*20,'before' =>$zongjian_find['money'], 'after' => $zongjian_data['money'], 'memo' => '分销身份分U']);

                        }elseif ($zongjian_find && !$jingli_find){
                            $zongjian_data=[
                                'id'=> $zongjian_find['id'],
                                'money'=>$zongjian_find['money']+$fenxiaogoods_number*50,
                            ];
                            $user_model->where('id',$zongjian_find['id'])->update(['money'=>$zongjian_data['money']]);
                            //总监分销身份分U记录创建
                            MoneyLog::create(['user_id' => $zongjian_find['id'], 'money' => $fenxiaogoods_number*50,'before' =>$zongjian_find['money'], 'after' => $zongjian_data['money'], 'memo' => '分销身份分U']);

                        }

                    }

                }

                //设备表给用户增加设备
                //查找顶级分类id开始
                $goodsClassList = collection(\app\admin\model\GoodsClass::select())->toArray();
                $items=array();
                foreach($goodsClassList as $v){ //将数组存入$items,且$items的键为$data中的id
                    $items[$v['id']] = $v;
                }
                $now_class_id_find=$goodsinfo['goods_class_id'];
                $topclassidfindarr=[];
                while(true)
                {
                    if($items[$now_class_id_find]['pid']==0){
                        $topclassidfindarr[1]=$now_class_id_find;
                        break;
                    }
                    if(isset($items[$now_class_id_find]['pid'])) {
                        if ($now_class_id_find == 0) {
                            break;
                        } else {
                            $now_class_id_find = $items[$now_class_id_find]['pid'];
                            array_unshift($topclassidfindarr, $now_class_id_find);
                        }
                    }else{
                        $topclassidfindarr[1]=null;
                        break;
                    }
                }
                //查找顶级分类id结束
                $allmachinedata=[];
                if(($user_parent_find['c_buy_number']-$u_buy_s-$orderinfo['quantity'])>0){
                    //参与分币的机器数据写入
                    for ($i=0; $i <  ($orderinfo['quantity']); $i++) {
                        $machinedata['user_id']=$userinfo['id'];
                        $machinedata['goods_id']=$orderinfo['goods_id'];
                        $machinedata['state']=0;
                        $machinedata['expirationtime']=$goodsinfo['contract_cycle']*24*60*60+time();
                        $machinedata['activestate']=1;
                        $machinedata['top_goods_class_id']=$topclassidfindarr[1];
                        $machinedata['level_up_condition']=0;
                        array_unshift($allmachinedata, $machinedata);
                    }

                }else if(($user_parent_find['c_buy_number']-$u_buy_s)<=0){
                    //不参与分币的机器数据写入
                    for ($i=0; $i < ($orderinfo['quantity']); $i++) {
                        $machinedata['user_id']=$userinfo['id'];
                        $machinedata['goods_id']=$orderinfo['goods_id'];
                        $machinedata['state']=0;
                        $machinedata['expirationtime']=$goodsinfo['contract_cycle']*24*60*60+time();
                        $machinedata['activestate']=1;
                        $machinedata['top_goods_class_id']=$topclassidfindarr[1];
                        $machinedata['level_up_condition']=1;
                        array_unshift($allmachinedata, $machinedata);
                    }
                }else if(($user_parent_find['c_buy_number']-$u_buy_s-$orderinfo['quantity'])<0 && ($user_parent_find['c_buy_number']-$u_buy_s)>=0){
                    $canyufenbi=$user_parent_find['c_buy_number']-$u_buy_s;
                    $bucanyufenbi=$orderinfo['quantity']-$canyufenbi;
                    //不参与分币的机器数据写入
                    for ($i=0; $i < ($bucanyufenbi); $i++) {
                        $machinedata['user_id']=$userinfo['id'];
                        $machinedata['goods_id']=$orderinfo['goods_id'];
                        $machinedata['state']=0;
                        $machinedata['expirationtime']=$goodsinfo['contract_cycle']*24*60*60+time();
                        $machinedata['activestate']=1;
                        $machinedata['top_goods_class_id']=$topclassidfindarr[1];
                        $machinedata['level_up_condition']=1;
                        array_unshift($allmachinedata, $machinedata);
                    }
                    //参与分币的机器数据写入
                    for ($i=0; $i <  ($canyufenbi); $i++) {
                        $machinedata['user_id']=$userinfo['id'];
                        $machinedata['goods_id']=$orderinfo['goods_id'];
                        $machinedata['state']=0;
                        $machinedata['expirationtime']=$goodsinfo['contract_cycle']*24*60*60+time();
                        $machinedata['activestate']=1;
                        $machinedata['top_goods_class_id']=$topclassidfindarr[1];
                        $machinedata['level_up_condition']=0;
                        array_unshift($allmachinedata, $machinedata);
                    }
                }
                $machineModel=new \app\admin\model\Machine;
                $machineModel->allowField(true)->saveAll($allmachinedata);


                Db::commit();
                $result = true;
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                dump($e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
                dump($e);
                $this->error($e->getMessage());
            }
        }
        if ($result !== false) {
            $this->success('支付成功',$order_sn);
        } else {
            $this->error(__('支付密码错误。'));
        }
    }
}
